cc.Class({
    extends: cc.Component,

    properties: {
        content: cc.Node,
    },

    onLoad() {
        this.lobbyMain = cc.find("Canvas").getComponent("lobbyMain");
        // this.tryInitLobbyInfo(5);
    },

    // tryInitLobbyInfo(retries) {
    //     // this.lobbyMain = this.node.parent.getComponent("lobbyMain");
    //     this.lobbyMain = cc.find("Canvas").getComponent("lobbyMain");

    //     // if (!this.lobbyMain) {
    //     //     if (retries > 0) {
    //     //         this.scheduleOnce(() => {
    //     //             this.tryInitLobbyInfo(retries - 1);
    //     //         }, 0.1);
    //     //     } else {
    //     //         console.warn("lobbyMain 获取失败，已达最大重试次数");
    //     //     }
    //     //     return;
    //     // }

    //     this.lobbyNet = this.lobbyMain.lobbyNet;
    //     this.playerInfo = this.lobbyMain.playerInfo;
    //     this.games = this.content.children;

    //     this.gameNode = this.lobbyMain.node.getChildByName("game")
    //     this.gameLoading = this.lobbyMain.node.getChildByName("game_loading");
    //     this.ProgressBar = this.gameLoading.getChildByName("jindu").getChildByName("task_pro2").getComponent(cc.ProgressBar)
    //     this.progressLabel = this.gameLoading.getChildByName("jindu").getChildByName("label").getComponent(cc.Label)
    // },

    start() {
        this.lobbyNet = this.lobbyMain.lobbyNet;
        this.playerInfo = this.lobbyMain.playerInfo;
        this.games = this.content.children;

        this.gameNode = this.lobbyMain.node.getChildByName("game")
        this.gameLoading = this.lobbyMain.node.getChildByName("game_loading");
        this.ProgressBar = this.gameLoading.getChildByName("jindu").getChildByName("task_pro2").getComponent(cc.ProgressBar)
        this.progressLabel = this.gameLoading.getChildByName("jindu").getChildByName("label").getComponent(cc.Label)
    },

    //点击游戏事件
    onClickGame(event, target) {
        this.enterGame(target);
    },


    onClick(event, target) {
        this.lobbyMain.playClickSound();
        if (target == "shouqi") { // 收起分类
            this.shouqiFenlei(false);
            this.node.getChildByName("shouqi").active = false;
        } else if (target == "zhankai") { // 展开分类
            this.shouqiFenlei(true);
            this.node.getChildByName("zhankai").active = false;
        }
    },

    shouqiFenlei(bool) {
        let fenLeiNode = this.node.getChildByName("fenlei");
        let viewNode = this.node.getChildByName("view");
        let moveX = 0;
        let opacity = 0;
        let sNode = null
        if (bool) {
            moveX = 80;
            opacity = 255;
            sNode = this.node.getChildByName("shouqi");
        } else {
            moveX = -80;
            opacity = 0;
            sNode = this.node.getChildByName("zhankai");
        }
        cc.tween(fenLeiNode)
            .to(0.3, { x: fenLeiNode.x + moveX })
            .call(() => {
                sNode.active = true
            })
            .start();

        cc.tween(viewNode)
            .to(0.3, { x: viewNode.x + moveX })
            .start();

        fenLeiNode.children.forEach(child => {
            const labelNode = child.getChildByName('label');
            const iconNode = child.getChildByName('icon');
            const liziNode = child.getChildByName('checkmark').getChildByName('icon_lizi');

            if (labelNode && iconNode && liziNode) {
                cc.tween(labelNode)
                    .to(0.3, { opacity: opacity })
                    .start();

                cc.tween(iconNode)
                    .to(0.3, { x: iconNode.x - moveX })
                    .start();

                cc.tween(liziNode)
                    .to(0.3, { x: liziNode.x - (moveX / 2) })
                    .start();
            }
        });
    },


    //进入游戏
    enterGame(gameName) {
        let prefabName = "game_" + gameName;
        this.lobbyMain.pauseMusic();
        this.gameLoading.active = true;
        let serverIp = this.lobbyMain.configJson.serverIp
        let port_hot = this.lobbyMain.configJson.port_hot

        let version_str = "version_" + gameName;
        let version = this.lobbyMain.configJson[version_str];
        console.log("加载游戏：" + gameName);
        console.log(JSON.stringify(this.lobbyMain.configJson));
        console.log(this.lobbyMain.configJson[version_str]);
        console.log("加载游戏：" + version_str);

        if (this.configJson.isDebug) {
            gameName = gameName;
        } else {
            gameName = "http://" + serverIp + ":" + port_hot + "/hotUpdate/" + gameName + "/v" + version;
        }
        this.loadGamePrefab(gameName, prefabName);
    },

    loadGamePrefab(gameName, prefabName) {
        // 加载 bundle
        let self = this;
        cc.assetManager.loadBundle(gameName, (err, bundle) => {
            if (err) {
                console.error('加载 bundle 失败:', err);
                self.lobbyMain.showTips("Failed to load the game.");
                this.gameLoading.active = false;
                return;
            }
            // 加载 bundle 中的预制体
            bundle.load(prefabName, cc.Prefab, (finished, total, item) => {
                let percent = ((finished / total) * 100).toFixed(2);
                self.ProgressBar.progress = percent / 100;
                self.progressLabel.string = percent + "%";
            }, (err, prefab) => {
                if (err) {
                    console.error('加载预制体失败:', err);
                    self.lobbyMain.showTips("Failed to load the game.");
                    this.gameLoading.active = false;
                    return;
                }

                console.log(`预制体 ${prefabName} 加载成功`);

                // 实例化预制体
                const node = cc.instantiate(prefab);
                self.gameNode.addChild(node);
                // this.gameLoading.active = false;  //需要注释
            });
        });
    },

    //加载游戏图标
    loadGameIcon(data) {
        this.games = this.content.children;
        for (let i = 0; i < this.games.length; i++) {
            let game = this.games[i];
            let gameInfo = data.find(item => {
                return item.name == game.name;
            });
            if (gameInfo) {
                let isNew = gameInfo.isNew;
                let isHot = gameInfo.isHot;
                let isShow = gameInfo.isShow;
                if (isShow == "false") {
                    game.active = false;
                } else {
                    game.active = true;
                }
                if (isHot == "true") {
                    game.getChildByName("hot").active = true;
                    game.zIndex = 0;
                } else {
                    game.getChildByName("hot").active = false;
                    game.zIndex = 1;
                }
                if (isNew == "true" && isHot == "false") {
                    game.getChildByName("new").active = true;
                } else {
                    game.getChildByName("new").active = false;
                }

            } else {
                game.active = false;
                continue;
            }
            let imagePath = "image/game/big/" + game.name;
            let bundle = cc.assetManager.getBundle("hall");
            if (bundle) {
                bundle.load(imagePath, cc.SpriteFrame, (err, spriteFrame) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    game.getComponent(cc.Sprite).spriteFrame = spriteFrame;
                });
            } else {
                cc.error("Bundle 'hall' not found");
            }
        }
    },

    //游戏状态更新
    gameStatusUpdated(data) {
        for (let i = 0; i < this.playerInfo.gameInfo.length; i++) {
            let temp = this.playerInfo.gameInfo[i];
            if (temp.gameId == data.gameId) {
                let isHot = data.isHot;
                let isShow = data.isShow;
                let isNew = data.isNew;
                if (isHot) {
                    temp.isHot = isHot;
                }
                if (isNew) {
                    temp.isNew = isNew;
                }
                if (isShow) {
                    temp.isShow = isShow;
                }
            }
        }
        for (let j = 0; j < this.games.length; j++) {
            let game = this.games[j];
            let gameInfo = this.playerInfo.gameInfo.find(item => {
                return item.name == game.name;
            });

            if (gameInfo) {
                let isNew = gameInfo.isNew;
                let isHot = gameInfo.isHot;
                let isShow = gameInfo.isShow;
                if (isShow == "false") {
                    game.active = false;
                } else {
                    game.active = true;
                }
                if (isHot == "true") {
                    game.getChildByName("hot").active = true;
                    game.zIndex = 0;
                } else {
                    game.getChildByName("hot").active = false;
                    game.zIndex = 1;
                }
                if (isNew == "true" && isHot == "false") {
                    game.getChildByName("new").active = true;
                } else {
                    game.getChildByName("new").active = false;
                }

            } else {
                game.active = false;
                continue;
            }
        }
    },

    //分类
    click_fenlei(event, name) {
        this.lobbyMain.playClickSound();
        switch (name) {
            case "all":
                break;
            case "love":
                break;
            case "slot":
                break;
            case "fish":
                break;
            case "other":
                break;
            default:
                break;
        }

        let skeleton = event.node.getChildByName("checkmark").getChildByName("icon_lizi").getComponent(sp.Skeleton);
        skeleton.setAnimation(0, 'animation', false);
        skeleton.setCompleteListener((trackEntry) => {
            if (trackEntry.animation.name === 'animation') {
                skeleton.setAnimation(0, 'animation2', true);
            }
        });
    },
});
